package com.xhtt.smart.card.server.handle;

import com.alibaba.fastjson.JSON;
import com.xhtt.smart.card.common.msg.bean.MsgServerBean;
import com.xhtt.smart.card.server.util.NettySocketHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author wangze
 * @date 2018-07-03 13:44.
 **/

public class NettyHandle extends SimpleChannelInboundHandler<MsgServerBean> {

    private final static Logger LOGGER = LoggerFactory.getLogger(NettyHandle.class);


    /**
     * 活跃状态
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("--- Client is active ---");
    }

    /**
     * 不活跃状态
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("--- Client is inactive ---");
        NettySocketHolder.remove((NioSocketChannel) ctx.channel());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;

            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                //LOGGER.info("已经10秒没有收到信息！");
                //TODO 向客户端发送信息
                //ctx.writeAndFlush(HEART_BEAT).addListener(ChannelFutureListener.CLOSE_ON_FAILURE) ;

            }


        }
        super.userEventTriggered(ctx, evt);
    }


    /**
     * 处理数据
     *
     * @param ctx
     * @param msgBean
     * @throws Exception
     */

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgServerBean msgBean) throws Exception {
        //TODO 保持连接
        LOGGER.info("收到MsgBean={}", JSON.toJSONString(msgBean));
        System.out.println("111111111111-"+msgBean.getDeviceType());
        System.out.println("222222222222-"+msgBean.getDeviceCode());

        System.out.println("33333333333&"+(msgBean.getData()[0]));
        System.out.println("33333333333&"+(msgBean.getData()[1]));
        System.out.println("33333333333&"+(msgBean.getData()[2]));
        //保存客户端与 Channel 之间的关系
        NettySocketHolder.put(msgBean.getDeviceType() + "-" + msgBean.getDeviceCode(), (NioSocketChannel) ctx.channel());


    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);

        System.out.println(cause);

    }
}